// 账号管理
// noinspection JSUnusedLocalSymbols

import {StorageUtils} from "@ginstone/common-utils/dist/src/utils/StorageUtils";
import {NgaClient} from "@ginstone/nga-api/dist/src/client/NgaClient";
import {NukeApi} from "@ginstone/nga-api/dist/src/method/NukeApi";
import querystring from "querystring";

// 在localStorage中保存cookie使用的前缀
const COOKIE_PREFIX = "cookie:"
// api使用的前缀key
const API_BASE_URL_KEY = "api:baseUrl"
// 当前账号key
const ACCOUNT_CURRENT_KEY = "account:current"
// 默认api前缀
const DEFAULT_PREFIX = "nga";
// 匿名用户的cookie
const ANONYMOUS_COOKIE = "ngaPassportUid=0;ngaPassportUrlencodedUname=%C4%E4%C3%FB%D3%C3%BB%A7;ngaPassportCid=xxx;";
// 通过cookie创建客户端
const buildClient = (baseUrl, cookie) => {
    const uid = /ngaPassportUid=(\d+);/.exec(cookie.toString())[1]
    return new NgaClient(`/${baseUrl}-${uid}`, cookie);
}

export default {
    namespaced: true,
    state: {
        // 客户端
        clients: [],
        // api前缀可选项
        baseUrls: [DEFAULT_PREFIX, "178", "ngabbs"],
        // 当前使用的api前缀
        baseUrl: DEFAULT_PREFIX,
        // 当前账号
        currentUid: undefined,
        // 当前账号信息
        currentUserInfo: undefined,
        // 当前账号的收藏版面
        currentFavorForum: undefined,
    },
    mutations: {
        method(state, payload) {

        },
        // 更新多个数据
        accountRefresh() {
            this.commit("Account/accountUserInfoRefresh")
            this.commit("Account/accountFavorForumRefresh")
        },
        //更新当前账号收藏版面
        accountFavorForumRefresh(state, payload) {
            if (state.currentUid) {
                const client = state.clients.filter(i => i.userId === state.currentUid)[0]
                if (client) {
                    NukeApi.favorForumList(client).then(res => {
                        state.currentFavorForum = res
                    })
                }
            }
        },
        //更新当前账号信息
        accountUserInfoRefresh(state) {
            if (state.currentUid) {
                const client = state.clients.filter(i => i.userId === state.currentUid)[0]
                if (client) {
                    NukeApi.userInfoGetById(client, state.currentUid).then(res => {
                        state.currentUserInfo = res
                    })
                }
            }
        },
        // 切换账号到指定userId
        accountSwitch(state, userId) {
            console.log("切换账号:" + userId)
            userId = Number(userId)
            const client = state.clients.filter(i => i.userId === userId)[0];
            if (client) {
                state.currentUid = userId
                StorageUtils.put(ACCOUNT_CURRENT_KEY, userId)
                // 更新当前账号信息
                this.commit("Account/accountRefresh")
                // 清空提醒消息
                this.commit("Notice/clear")


            } else {
                throw "不存在该账号"
            }
        },
        // 保存账号cookie到localStorage
        accountSave(state) {
            state.clients.forEach(c => StorageUtils.put(COOKIE_PREFIX + c.userId, c.cookie))
        },
        /**
         * 添加账号
         * @param state
         * @param cookie cookie
         */
        accountAdd(state, cookie) {
            const client = buildClient(state.baseUrl, cookie)
            state.clients = state.clients.filter(i => i.userId !== client.userId)
            state.clients.push(client)
            StorageUtils.put(COOKIE_PREFIX + client.userId, client.cookie)
        },
        accountDel(state, userId) {
            state.clients = state.clients.filter(i => i.userId !== userId)
            this.commit("Account/accountSave")
            StorageUtils.del(COOKIE_PREFIX + userId)
            if (state.currentUid === userId && state.clients.length > 0) {
                this.commit("Account/accountSwitch", state.clients[0].userId)
            }
        },
        // 初始化
        accountInit(state, payload) {
            // 前缀
            state.baseUrl = StorageUtils.get(API_BASE_URL_KEY) || DEFAULT_PREFIX
            // 所有账号的cookie
            const cookies = StorageUtils.getValueByPrefix(COOKIE_PREFIX);
            // 客户端
            const clients = cookies.map(cookie => buildClient(state.baseUrl, cookie))
            state.clients = clients
            if (clients.length === 0) {
                clients.push(buildClient(state.baseUrl, ANONYMOUS_COOKIE))
            }
            if (clients.length > 0) {
                console.log("已登陆账号", clients.map(({userId, username}) => {
                    return {userId, username}
                }))
            }
            // 选择当前账号

            // 从地址栏获取账号uid
            const account = querystring.parse(window.location.search.substring(1)).account
            const qs = account ? Number(account) : undefined;
            const uid = Number(StorageUtils.get(ACCOUNT_CURRENT_KEY));

            state.currentUid = qs || uid || (clients.length > 0 ? clients[0].userId : undefined)
            this.commit("Account/accountRefresh")
            // if (uid) {
            //     // 有当前账号
            //     state.currentUid = uid
            // } else if (clients.length > 0) {
            //     // 无当前账号,且有客户端, 使用第一个客户端作为当前账号
            //     this.commit("Account/accountSwitch", clients[0].userId)
            // }

        },

    },
    actions: {
        method: ({dispatch, commit, state, rootGetters}, payload) => {

        },
    },
    getters: {
        /**
         * 获取客户端
         * @param state
         * @param userId 用户id，不传则使用当前用户id
         * @returns {*}
         */
        getClient: (state) => (userId) => {
            userId = userId | state.currentUid
            return state.clients.filter(i => i.userId === userId)[0];
        },
        /**
         * 获取所有客户端
         * @returns {[]}
         */
        getAllClients: (state) => {
            return state.clients
        },
    },
}